package com.codegravity.mobile.expensms;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;

public class Filter extends Activity implements OnClickListener {
	static DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
	final static String smsInbox = "content://sms/inbox";
	EditText txt_keyStr, txt_keyNum, txt_decimal;
	Button btn_test, btn_save, btn_reset;
	RadioGroup radGrp = null;
	RadioButton radMon = null, radSun = null;
	SharedPreferences myPrefs;
	String s_number, s_debstr;
	DecimalFormat df = new DecimalFormat("#.##");
	float amount;
	String testRes = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		myPrefs = getSharedPreferences("SMSExpense", MODE_WORLD_READABLE);
		setContentView(R.layout.scrn_filter);
		initGUI();
		btn_reset.setOnClickListener(this);
		btn_save.setOnClickListener(this);
		btn_test.setOnClickListener(this);
		loadFilter();
	}

	private void loadFilter() {
		radGrp.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				SharedPreferences.Editor prefsEditor = myPrefs.edit();
				if (checkedId == radMon.getId()) {
					prefsEditor.putBoolean("weekSun", false);
				} else if (checkedId == radSun.getId()) {
					prefsEditor.putBoolean("weekSun", true);
				}
				prefsEditor.commit();
			}
		});

		if (myPrefs.getBoolean("weekSun", false)) {
			radSun.setChecked(true);
		} else {
			radMon.setChecked(true);
		}
		txt_keyNum.setText(myPrefs.getString("keynum", ""));
		txt_keyStr.setText(myPrefs.getString("keystr", ""));
		txt_decimal.setText(myPrefs.getString("keydec", "."));
	}

	private void initGUI() {
		txt_keyNum = (EditText) findViewById(R.id.key_numb);
		txt_keyStr = (EditText) findViewById(R.id.key_str);
		btn_reset = (Button) findViewById(R.id.btn_reset);
		btn_save = (Button) findViewById(R.id.btn_save);
		btn_test = (Button) findViewById(R.id.btn_test);
		radGrp = (RadioGroup) findViewById(R.id.chk_weekstart);
		radMon = (RadioButton) findViewById(R.id.opt_mon);
		radSun = (RadioButton) findViewById(R.id.opt_sun);
		txt_decimal = (EditText) findViewById(R.id.txt_dec);
	}

	@Override
	public void onClick(View v) {
		if (btn_reset.getId() == v.getId()) {
			txt_keyNum.setText("");
			txt_keyStr.setText("");
		} else if (btn_save.getId() == v.getId()) {
			saveFilter();
			finish();
		} else if (btn_test.getId() == v.getId()) {

			String SORT_ORDER = "date DESC";
			int count = 0;

			s_number = txt_keyNum.getText().toString();
			s_debstr = txt_keyStr.getText().toString();
			System.out.println("Searching numb " + s_number);
			Cursor cursor = getApplicationContext().getContentResolver().query(
					Uri.parse(smsInbox),
					new String[] { "_id", "thread_id", "address", "person",
							"date", "body" }, "address ='" + s_number + "'",
					null, SORT_ORDER);

			if (cursor != null) {
				try {
					count = cursor.getCount();
					if (count > 0) {
						cursor.moveToFirst();
						do {
							int idx1 = cursor.getString(5).indexOf(
									txt_keyStr.getText().toString());
							if (idx1 == -1)
								continue;
							int idx2 = cursor.getString(5).indexOf("\n", idx1);
							if (idx2 == -1)
								idx2 = cursor.getString(5).length();
							Pattern MY_PATTERN = Pattern.compile("[0-9|"
									+ txt_decimal.getText().toString() + "]+");
							Matcher m = MY_PATTERN.matcher(cursor.getString(5)
									.substring(idx1, idx2));
							while (m.find()) {
								amount = Float.parseFloat(m.group().replaceAll(
										",", "."));

								testRes = testRes + "\n Number: " + s_number
										+ "\n Amount: " + df.format(amount)
										+ "\n Date: "
										+ formatter.format(cursor.getLong(4));
								break;
							}
						} while (cursor.moveToNext());
						showDialog(0);
					}
				} finally {
					cursor.close();
				}
			}

		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		AlertDialog dialog = null;
		AlertDialog.Builder alertBuilder;
		alertBuilder = new AlertDialog.Builder(this);

		alertBuilder.setTitle("Filter Test");
		alertBuilder.setMessage(testRes);
		alertBuilder.setPositiveButton("Save Filter",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.dismiss();
						saveFilter();
					}
				});

		alertBuilder.setNegativeButton("Reset",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.dismiss();
						txt_keyNum.setText("");
						txt_keyStr.setText("");
					}
				});
		dialog = alertBuilder.create();
		dialog.setCancelable(false);
		dialog.show();
		return dialog;
	}

	private void saveFilter() {
		SharedPreferences.Editor prefsEditor = myPrefs.edit();
		prefsEditor.putString("keynum", txt_keyNum.getText().toString());
		prefsEditor.putString("keystr", txt_keyStr.getText().toString());
		prefsEditor.putString("keydec", txt_decimal.getText().toString());
		prefsEditor.commit();
	}
}
